package com.aduerr.v1shouyin.mvp.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.entity.CardType;
import com.aduerr.v1shouyin.entity.KaQuanXiangQingEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.mvp.activity.CardDetailNewActivity;
import com.aduerr.v1shouyin.mvp.activity.HexiaoJiluActivity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter;
import se.emilsjolander.stickylistheaders.StickyListHeadersListView;

import static com.aduerr.v1shouyin.App.getApp;


/**
 * 类名: YouhuiFragment
 * 此类用途: ---
 *
 * @Date: 2017-10-24 15:42
 * @FileName: com.aduer.shouyin.mvp.fragment.YouhuiFragment.java
 */
public class TuanGouFragment extends Fragment {

    @BindView(R.id.stickylist_1)
    StickyListHeadersListView stickylist;
    @BindView(R.id.srfv)
    SmartRefreshLayout srl;
    @BindView(R.id.empty_view)
    View empty_view;
    Unbinder unbinder;
    ArrayList<KaQuanXiangQingEntity.DataBean.ListBean> bodylist = new ArrayList<>();
    //请求,码 页数
    private int pager = 1;
    //根据页码判断是否还有更多的数据
    private boolean hasMore = false;
    private TuanGouFragment.stickListAdpterYOU stickListAdpter;
    private int headsize;
    private TextView tvEmpty;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View inflate =
                LayoutInflater.from(getActivity()).inflate(R.layout.fragment_hx_zhekou,
                        null, false);
        unbinder = ButterKnife.bind(this, inflate);
        return inflate;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        stickListAdpter = new stickListAdpterYOU(getActivity());
        stickylist.setAdapter(stickListAdpter);
        stickylist.setVerticalScrollBarEnabled(false);
        stickylist.setFastScrollEnabled(false);
        tvEmpty = (TextView) empty_view.findViewById(R.id.tv_empty);

        HexiaoJiluActivity activity = (HexiaoJiluActivity) getActivity();
        ViewPager vpHexiao = activity.getVpHexiao();
        vpHexiao.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset,
                                       int positionOffsetPixels) {
                Log.e("22", "onPageScrolled");
                if(srl != null) {
                    Log.e("22", "onPageScrolled走了吗55555");
                    srl.finishLoadmore();
                }
            }

            @Override
            public void onPageSelected(int position) {
                Log.e("22", "onPageSelected");
                if(srl != null) {
                    Log.e("22", "onPageScrolled走了吗55555");
                    srl.finishLoadmore();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                Log.e("22", "onPageScrollStateChanged");

            }
        });


        initUI();
        initData();
    }

    public void initUI() {

        srl.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                hasMore = true;
                if(!srl.isRefreshing()) {
                    new Handler().postDelayed(() -> {
                        pager = pager + 1;
                        loadMoreData(pager);
                        // 加载完数据设置为不加载状态，将加载进度收起来
                        if(srl != null) {
                            refreshlayout.finishLoadmore();
                        }
                    }, 2000);
                }
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                initData();
                refreshlayout.finishRefresh();
            }
        });
//
//        //设置向下拉的时候的监听
//        srl.setOnRefreshListener(() -> {
//            //向下拉的时候加载数据
//            initData();
//            srl.setRefreshing(false);
//            srl.setLoading(false);
//        });
//        // 设置上拉加载更多
//        srl.setOnLoadMoreListener(() -> {
////                pager = pager + 1;
////                loadMoreData(pager);
////                srl.setLoading(false);
//            hasMore = true;
//            if (!srl.isRefreshing()) {
//
//
//                new Handler().postDelayed(() -> {
//                    pager = pager + 1;
//
//                    loadMoreData(pager);
//                    // 加载完数据设置为不加载状态，将加载进度收起来
//                    if (srl != null) {
//                        srl.setLoading(false);
//                    }
//                }, 2000);
//            }
//
//        });


    }

    //上拉加载数据
    private void loadMoreData(int pager) {
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("page", pager + "");
        addParams.put("type", "5");
//        heXiaoAllFregmenet.showProgress();
        APIRetrofit.getAPIService().getKaQuanXiangQingDetail(RXRequest.getXingPosParams(addParams, getContext()))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<KaQuanXiangQingEntity>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull KaQuanXiangQingEntity kaQuanXiangQingEntity) {
//                        if (isViewAttached())
                        int success = kaQuanXiangQingEntity.getSuccess();
                        if(success == 1) {
                            //请求成功后整合数据
                            onHexiaoAllFragView(kaQuanXiangQingEntity);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(getApp().getApplicationContext(), "网络异常",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(getApp().getApplicationContext(), "连接失败",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e("onError:", "error:" + e.getMessage());//R.string
                            // .checknet +
                            Toast.makeText(getApp().getApplicationContext(), "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    //下啦刷新
    public void initData() {
        getDataRefres(getContext(), pager + "");
    }

    private void getDataRefres(Context mContext, String page) {
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("page", "1");
        addParams.put("type", "5");
        APIRetrofit.getAPIService().getKaQuanXiangQingDetail(RXRequest.getXingPosParams(addParams, mContext))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<KaQuanXiangQingEntity>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull KaQuanXiangQingEntity kaQuanXiangQingEntity) {
                        int success = kaQuanXiangQingEntity.getSuccess();
                        if(success == 1) {
                            //请求成功后整合数据
//                            if (kaQuanXiangQingEntity.getData().size()<0){
//                                empty_view.setVisibility(View.VISIBLE);
//                                tvEmpty.setText("暂没有该类型的卡券核销记录");
//                            }else {
                            onHexiaoAllFragView(kaQuanXiangQingEntity);
//                            }

                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(getApp().getApplicationContext(), "网络异常",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(getApp().getApplicationContext(), "连接失败",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e("onError:", "error:" + e.getMessage());//R.string
                            // .checknet +
                            Toast.makeText(getApp().getApplicationContext(), "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    //从网络上请求下来的数据在
    public void onHexiaoAllFragView(KaQuanXiangQingEntity kaQuanXiangQingEntity) {
//        srl.setRefreshing(false);
//        if (kaQuanXiangQingEntity.getPageCount() > pager) {
//            //有更多的数据
//            hasMore = true;
//        } else {
//            hasMore = false;
//        }
        //// TODO: 2017/10/24 0024    整合数据,展示列表//上拉加载
        if(hasMore) {
            if(kaQuanXiangQingEntity.getSuccess() == 1) {
                List<KaQuanXiangQingEntity.DataBean> data =
                        kaQuanXiangQingEntity.getData();
                int size = data.size();
//                headsize = size;
                //判断数据时候为空
//                if (size == 0) {
//                    ToastUtils.showToast(getContext(), "没有更多的数据了");
//                    return;
//                }
                if(size > 0) {
                    //下啦刷新前把数据清空
//                    bodylist.clear();
                    for(int i = 0; i < size; i++) {
                        KaQuanXiangQingEntity.DataBean dataBean = data.get(i);
                        List<KaQuanXiangQingEntity.DataBean.ListBean> list =
                                dataBean.getList();
                        for(KaQuanXiangQingEntity.DataBean.ListBean listBean : list) {
                            listBean.setHeadId(i + headsize - 1);
                            bodylist.add(listBean);
                        }
                        //头部id需要整合
                        headsize++;
                    }

                    if(stickListAdpter != null) {
                        stickListAdpter.setBodyList(bodylist);
                    }

                }

            }
//下啦刷新
        } else {
            if(kaQuanXiangQingEntity.getSuccess() == 1) {
                List<KaQuanXiangQingEntity.DataBean> data =
                        kaQuanXiangQingEntity.getData();
                int size = data.size();
                headsize = size;
                //判断数据时候为空
                if(size > 0) {
                    empty_view.setVisibility(View.GONE);
                    //下啦刷新前把数据清空
                    bodylist.clear();
                    for(int i = 0; i < size; i++) {
                        KaQuanXiangQingEntity.DataBean dataBean = data.get(i);
                        List<KaQuanXiangQingEntity.DataBean.ListBean> list =
                                dataBean.getList();
                        for(KaQuanXiangQingEntity.DataBean.ListBean listBean : list) {
                            listBean.setHeadId(i);
                            bodylist.add(listBean);
                        }
                    }

                    if(stickListAdpter != null) {
                        stickListAdpter.setBodyList(bodylist);
                    }

                } else {
                    empty_view.setVisibility(View.VISIBLE);
                    tvEmpty.setText("暂没有该类型的卡券核销记录");
                }

            }
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        bodylist.clear();
    }

    class stickListAdpterYOU extends BaseAdapter implements StickyListHeadersAdapter {
        private Context context;
        private List<KaQuanXiangQingEntity.DataBean.ListBean> bodyList =
                new ArrayList<>();

        public stickListAdpterYOU(Context activity) {
            this.context = activity;
        }

        //整合好的数据
        public void setBodyList(ArrayList<KaQuanXiangQingEntity.DataBean.ListBean> bodylist) {
            this.bodyList = bodylist;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return bodyList != null ? bodyList.size() : 0;
        }

        @Override
        public Object getItem(int position) {
            return bodyList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            BodyHolder bodyHolder = null;
            if(convertView == null) {
                convertView =
                        LayoutInflater.from(context).inflate(R.layout.item_fragment_hexiao, parent, false);
                bodyHolder = new BodyHolder(convertView);
                convertView.setTag(bodyHolder);
            } else {
                bodyHolder = (BodyHolder) convertView.getTag();
            }
            //条目的设置数据
            bodyHolder.tv_hx_title.setText(bodyList.get(position).getName());
            bodyHolder.tv_hx_zhekou.setText(bodyList.get(position).getDescription());
            String usetime = bodyList.get(position).getUsetime();
            String[] split = usetime.split(" ");
            if(split.length >= 2) {
                bodyHolder.tv_hx_time.setText(split[1]);
            } else {
                bodyHolder.tv_hx_time.setText("");
            }

            bodyHolder.tv_hx_seller.setText(bodyList.get(position).getSiteusername());
//            //设置数据
//            String paytype = bodyList.get(position).getPaytype();

            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    KaQuanXiangQingEntity.DataBean.ListBean listBean =
                            bodyList.get(position);
                    Intent intent = new Intent(getActivity(),
                            CardDetailNewActivity.class);
                    intent.putExtra("type", CardType.WX.name());
                    intent.putExtra("Data", listBean);
//                    intent.putExtra("erWeiMaResult", erWeiMaResult);
                    intent.putExtra("tag", "xianxia");
                    startActivity(intent);
                }
            });
            return convertView;
        }

        @Override
        public View getHeaderView(int position, View convertView, ViewGroup parent) {
            HeadHolder headHolder = null;
            if(convertView == null) {
                convertView =
                        LayoutInflater.from(context).inflate(R.layout.item_pmr_header_hexiao, parent, false);
                headHolder = new HeadHolder(convertView);
                convertView.setTag(headHolder);
            } else {
                headHolder = (HeadHolder) convertView.getTag();
            }
            //设置数据
            headHolder.tvTime.setText(bodyList.get(position).getDate());
            return convertView;
        }

        @Override
        public long getHeaderId(int position) {
            return bodyList.get(position).getHeadId();
        }

        //头部的内部类
        class HeadHolder {
            private TextView tvTime;

            public HeadHolder(View itemHeadView) {
                tvTime = (TextView) itemHeadView.findViewById(R.id.tv_time);
            }
        }

        //内容的内部类
        class BodyHolder {
            private final TextView tv_hx_title;
            private final TextView tv_hx_zhekou;
            private final TextView tv_hx_time;
            private final TextView tv_hx_seller;

            public BodyHolder(View itemBodyView) {
                tv_hx_title = (TextView) itemBodyView.findViewById(R.id.tv_hx_title);
                tv_hx_zhekou = (TextView) itemBodyView.findViewById(R.id.tv_hx_zhekou);
                tv_hx_time = (TextView) itemBodyView.findViewById(R.id.tv_hx_time);
                tv_hx_seller = (TextView) itemBodyView.findViewById(R.id.tv_hx_seller);
            }
        }


    }
}
